<!--  -->
<template>
    <div class='recipeDetails'>
        <Drawer v-model="isShow" width="80%" :styles="styles" draggable mask-closable style="z-index: 2;">
            <cus-card class="mb_24">
                <div class="recipeDetails-title">
                    <div class="recipeDetails-title-left">{{ recipDetails.name }}</div>
                    <Button type="primary" size="small" :style="{ color: '#ffffff', padding: '2px 8px' }"
                        @click="openFenxi">营养分析图</Button>
                </div>
                <div class="recipeDetails-table">
                    <div class="recipeDetails-table-header">
                        <div class="recipeDetails-table-header-item" style="flex: 0.7;border-left: 0px;">餐段</div>
                        <div class="recipeDetails-table-header-item" v-for="(item, index) of timeList" :key="index">
                            {{ item.name }}({{ dateList[index] }})</div>
                    </div>
                    <div class="recipeDetails-table-content">
                        <div class="recipeDetails-table-content-item" v-for="(items, key, ind) in data" :key="ind">
                            <div class="recipeDetails-table-content-item-title">{{ key | mealTimeName(mealTimeList) }}</div>
                            <div class="recipeDetails-table-content-item-conter" v-for="(item, num) in items.dayMealSort"
									:key="num">
                                <div class="recipeDetails-table-content-item-conter-it" v-for="(it, ind) of item.food" :key="ind">
                                    <div style="color: #00B067;">{{ it.name }}</div>
                                    <div>{{ it.dishWeight }}g</div>
                                </div>
                                <div v-if="item.food.length > 0" class="recipeDetails-table-content-item-conter-itNumber">{{ item.repastNumber }}人</div>
                                <div v-else
                                    style="height: 100%;display: flex; align-items: center; justify-content: center;">暂不开餐
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </cus-card>

            <div style="height: 300px;">
                <!-- 食谱营养评估详情 -->
                <nutritionModal :dataItem="nutritionData" :dateStrList="timeList" :dateList="dateList">
                </nutritionModal>
            </div>

            <!-- 食谱营养评估 图表 -->
            <nutritionChart ref="nutritionChart" :dataItem="nutritionData" :dateStrList="timeList" :dateList="dateList">
            </nutritionChart>
            <Spin size="large" fix v-if="loading"></Spin>
        </Drawer>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { RecipeDetail, RecipeAssessment } from '@/api/organ/dishesModule'
import nutritionModal from './nutritionModal.vue'
import nutritionChart from './nutritionChart.vue'
export default {
    //import引入的组件需要注入到对象中才能使用
    components: { nutritionModal, nutritionChart },
    data() {
        //这里存放数据
        return {
            id: '',
            isShow: false,
            loading: true,
            data: {},
            recipDetails: {}, //食谱详情
            styles: {
                height: "calc(100% - 9px)",
                overflow: "auto",
                paddingBottom: "9px",
                position: "static",
            },
            timeList: [
                { name: '星期一', slot: 'one' },
                { name: '星期二', slot: 'two' },
                { name: '星期三', slot: 'three' },
                { name: '星期四', slot: 'four' },
                { name: '星期五', slot: 'five' },
                { name: '星期六', slot: 'six' },
                { name: '星期日', slot: 'seven' },
            ],
            foodPayList: [{ name: '伙食费' },
            { name: '就餐人数' },
            { name: '金额' }
            ],
            nutritionData: {
            },
            dateList: [], // 日期合集
            nums: ['one', 'two', 'three', 'four', 'five', 'six', 'seven'],
            mealTimeList: [
                { label: 'breakfast', name: '早餐', type: 0, index: 1 },
                { label: 'betwwenMealOne', name: '早~午间餐', type: 3, index: 2 },
                { label: 'lunch', name: '午餐', type: 1, index: 3 },
                { label: 'betwwenMealTwo', name: '午~晚间餐', type: 4, index: 1 },
                { label: 'supper', name: '晚餐', type: 2, index: 4 },
                { label: 'midnightMealOne', name: '夜餐1', type: 5, index: 5 },
                { label: 'midnightMealTwo', name: '夜餐2', type: 6, index: 6 }
            ],//餐段列表
        };
    },
    // 餐次名称过滤
    filters: {
        mealTimeName(value, mealTimeList) {
            let a = mealTimeList.filter(item => item.label == value);
            return a.length ? a[0].name : '';
        }
    },
    methods: {
        show() {
            this.isShow = true;
            this.getRecipeDetailAApi()
            this.getRecipeAssessment()
        },
        click(row) {
            console.log(row);
        },
        // 营养分析按钮
        openFenxi() {
            this.$refs["nutritionChart"].show();
        },
        // 获取本周日期组件处理
        getCurrentWeek(date) {
            let nowData = new Date(date); //传入时间参数,如 2021-11-09 获取给定日期所属的周 日期
            let currentDay = nowData.getDay();
            if (currentDay == 0) {
                currentDay = 7;
            }
            let beforweek = [],
                afterWeek = [];
            for (let i = 1; i <= 7; i++) {
                if (currentDay - i >= 0) {
                    let DayTime =
                        nowData.getTime() -
                        (currentDay - i) * 24 * 60 * 60 * 1000;
                    beforweek.push(new Date(DayTime).Format("yyyy-MM-dd"));
                } else {
                    let DayTime =
                        nowData.getTime() + (8 - i) * 24 * 60 * 60 * 1000;
                    afterWeek.push(new Date(DayTime).Format("yyyy-MM-dd"));
                }
            }
            afterWeek = afterWeek.reverse();
            this.dateList = [...beforweek, ...afterWeek];
        },
        // 获取食谱详情
        getRecipeDetailAApi() {
            this.loading = true;
            return new Promise((resolve) => {
                RecipeDetail({
                    mealPlanId: this.id
                }).then((res) => {
                    this.loading = false;
                    let deData = {};
                    if (res.code === 1) {
                        if (res.data.meal_plan.meal_plan_id != 0) {
                            // 得到食谱详情
                            this.recipDetails = res.data.meal_plan
                            // 获取食谱周期
                            this.getCurrentWeek(res.data.meal_plan.begian_time)
                        }
                        let aMealTimeList = []
                        aMealTimeList = [
                            { label: 'breakfast', name: '早餐', type: 0 },
                            { label: 'lunch', name: '午餐', type: 1 },
                            { label: 'supper', name: '晚餐', type: 2 },
                        ]
                        let copyList = [
                            { label: 'betwwenMealOne', name: '早~午间餐', type: 3 },
                            { label: 'betwwenMealTwo', name: '午~晚间餐', type: 4 },
                            { label: 'midnightMealOne', name: '夜餐1', type: 5 },
                            { label: 'midnightMealTwo', name: '夜餐2', type: 6 }
                        ]
                        copyList.forEach((item) => {
                            for (const key in res.data[item.label].dayMeal) {
                                if (res.data[item.label].dayMeal[key].food.length > 0) {
                                    aMealTimeList.push(item);
                                    return
                                }
                            }
                        })
                        aMealTimeList.forEach(item => {
                            for (const key in res.data) {
                                if (item.label == key) {
                                    console.log(res.data[key])
                                    deData[key] = res.data[key]
                                }
                            }
                        })
                        this.mealTimeList.forEach(item => {
                            console.log('1111111111',item);
                            for (let key in deData) {
                                if (item.label == key) {
                                    deData[key].index = item.index
                                    deData[key].dayMealSort = []
                                }
                            }
                        })
                        // 食谱每周对应排序
                        this.nums.forEach( (item,index) => {
                            for(let key in deData) {
                               for(let key1 in deData[key].dayMeal){
                                if(item == key1) {
                                    deData[key].dayMealSort[index] = deData[key].dayMeal[key1]
                                }
                               }

                            }
                        })
                        this.data = this.objValueSort(deData, 'index')
                        console.log('111111111111111',this.data);
                        resolve();
                    }
                });
            });
        },
        // 对食谱详情的周进行排序
        dealMealSort() {
           this.data.forEach(item => {
            console.log('1111111111',item);
           })
        },
        // 对象排序
        objValueSort(obj, key, sortType) { // 排序的函数
            // 1.根据数组中的对象的“xxx”，得到排序后的key，return y-x 表示降序  x-y 表示升序
            const newkey = Object.keys(obj).sort((a, b) => {
                let x = Number(obj[a][key]);
                let y = Number(obj[b][key]);
                if (sortType) {
                    return y - x;
                } else {
                    return x - y;
                }
            });
            // 2.用排序后的key构建新的对象数组
            const newObj = {};// 创建一个新的对象，用于存放排好序的键值对
            for (let i = 0; i < newkey.length; i++) { // 遍历newkey数组
                newObj[newkey[i]] = obj[newkey[i]];// 向新创建的对象中按照排好的顺序依次增加键值对
                newObj[newkey[i]].index = i + 1;
            }
            return newObj;// 返回排好序的新对象
        },
        // 食谱评估
        getRecipeAssessment() {
            this.loading = true;
            return new Promise((resolve) => {
                RecipeAssessment({
                    mealPlanId: this.id
                }).then((res) => {
                    this.loading = false;
                    if (res.code === 1) {
                        this.nutritionData = JSON.parse(res.data);
                        console.log('营养评估', this.nutritionData);
                        resolve();
                    }
                });
            });

        }
    },
}
</script>
<style scoped lang="less">
.recipeDetails {
    &-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        &-left {
            font-size: 18px;
            font-weight: 600;
            color: rgba(0, 0, 0, 0.85);
        }
    }

    &-table {
        max-height: 450px;
        overflow: auto;

        &-header {
            width: 100%;

            display: flex;
            background-color: #F1F6FF;
            border: 1px solid #D8DDE3;

            &-item {
                flex: 1;
                width: 170px;
                height: 49px;
                text-align: center;
                color: #657180;
                font-size: 14px;
                font-weight: 600;
                line-height: 49px;
                border-left: 1px solid #D8DDE3;
            }
        }

        &-content {
            border-left: 1px solid #D8DDE3;
            border-right: 1px solid #D8DDE3;

            &-item {
                display: flex;
                //    align-items: center;
                min-height: 48px;
                text-align: center;
                border-bottom: 1px solid #D8DDE3;

                &-title {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    flex: 0.7;
                    min-height: 48px;
                }

                &-conter {
                    position: relative;
                    flex: 1;
                    min-height: 48px;
                    border-left: 1px solid #D8DDE3;
                    padding: 10px 0 20px 0;

                    &-it {
                        display: flex;
                        justify-content: space-between;
                        padding: 0 14px;
                    }
                    &-itNumber {
                        position: absolute;
                        bottom: 0;
                        width: 100%;
                        text-align: center;
                    }
                }
            }

        }
    }
}
</style>